package ltd.flyweight.liquibasehelper.module.zngk.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import liquibase.change.ColumnConfig;
import liquibase.change.core.InsertDataChange;
import liquibase.changelog.ChangeSet;
import liquibase.serializer.core.yaml.YamlChangeLogSerializer;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import ltd.flyweight.liquibasehelper.module.zngk.dao.dbservice.ZngkSysDictDataDbService;
import ltd.flyweight.liquibasehelper.module.zngk.dao.dbservice.ZngkSysDictTypeDbService;
import ltd.flyweight.liquibasehelper.module.zngk.dao.entity.ZngkSysDictDataEntity;
import ltd.flyweight.liquibasehelper.module.zngk.dao.entity.ZngkSysDictTypeEntity;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ZngkSysDictService {

    private final ZngkSysDictTypeDbService zngkSysDictTypeDbService;
    private final ZngkSysDictDataDbService zngkSysDictDataDbService;

    @SneakyThrows
    public void runTaskGenDictTypeAndDataFromZngkLiquibaseYmlScript(String dictType, String newDictId) {
        ZngkSysDictTypeEntity dictTypeEntity = zngkSysDictTypeDbService.getOne(
                Wrappers
                        .lambdaQuery(ZngkSysDictTypeEntity.class)
                        .eq(ZngkSysDictTypeEntity::getId, dictType)
        );
        log.info("dictTypeEntity={}", dictTypeEntity);
        List<ZngkSysDictDataEntity> dictDataEntityList = zngkSysDictDataDbService.list(
                Wrappers
                        .lambdaQuery(ZngkSysDictDataEntity.class)
                        .eq(ZngkSysDictDataEntity::getDictionaryTypeId, dictType)
                        .orderByAsc(
                                ZngkSysDictDataEntity::getSortIndex,
                                ZngkSysDictDataEntity::getValue,
                                ZngkSysDictDataEntity::getName,
                                ZngkSysDictDataEntity::getId
                        )
        );
        log.info("dictDataEntityList={}", dictDataEntityList);

        ChangeSet changeSet = new ChangeSet(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmm-01")), "周立山", false, false, null, null, null, true, null);
        changeSet.setComments("sys_dict_type增加%s字典".formatted(dictTypeEntity.getName()));
        InsertDataChange insertDictTypeChange = new InsertDataChange();
        insertDictTypeChange.setTableName("sys_dict_type");
        insertDictTypeChange.addColumn(ColumnConfig.fromName("dict_id").setValue(newDictId));
        insertDictTypeChange.addColumn(ColumnConfig.fromName("tenant_id").setValue("000000"));
        insertDictTypeChange.addColumn(ColumnConfig.fromName("dict_name").setValue(dictTypeEntity.getName()));
        insertDictTypeChange.addColumn(ColumnConfig.fromName("dict_type").setValue(dictType));
        insertDictTypeChange.addColumn(ColumnConfig.fromName("create_dept").setValue("103"));
        insertDictTypeChange.addColumn(ColumnConfig.fromName("create_by").setValue("1"));
        insertDictTypeChange.addColumn(ColumnConfig.fromName("create_time").setValue("now()"));
        insertDictTypeChange.addColumn(ColumnConfig.fromName("remark").setValue(dictTypeEntity.getName()));
        changeSet.addChange(insertDictTypeChange);
        int i = 0;
        for (ZngkSysDictDataEntity zngkSysDictDataEntity : dictDataEntityList) {
            i++;
            InsertDataChange insertDictDataChange = new InsertDataChange();
            insertDictDataChange.setTableName("sys_dict_data");
            insertDictDataChange.addColumn(ColumnConfig.fromName("dict_code").setValue("%s%02d".formatted(newDictId, i)));
            insertDictDataChange.addColumn(ColumnConfig.fromName("tenant_id").setValue("000000"));
            insertDictDataChange.addColumn(ColumnConfig.fromName("dict_sort").setValue("%s".formatted(zngkSysDictDataEntity.getSortIndex())));
            insertDictDataChange.addColumn(ColumnConfig.fromName("dict_label").setValue(zngkSysDictDataEntity.getName()));
            insertDictDataChange.addColumn(ColumnConfig.fromName("dict_value").setValue(zngkSysDictDataEntity.getValue()));
            insertDictDataChange.addColumn(ColumnConfig.fromName("dict_type").setValue(zngkSysDictDataEntity.getDictionaryTypeId()));
            insertDictDataChange.addColumn(ColumnConfig.fromName("list_class").setValue("primary"));
            insertDictDataChange.addColumn(ColumnConfig.fromName("is_default").setValue(zngkSysDictDataEntity.getAsDefault() == 1 ? "Y" : "N"));
            insertDictDataChange.addColumn(ColumnConfig.fromName("create_dept").setValue("103"));
            insertDictDataChange.addColumn(ColumnConfig.fromName("create_by").setValue("1"));
            insertDictDataChange.addColumn(ColumnConfig.fromName("create_time").setValue("now()"));
            insertDictDataChange.addColumn(ColumnConfig.fromName("remark").setValue(zngkSysDictDataEntity.getRemark()));
            changeSet.addChange(insertDictDataChange);
        }

        // 创建YAML序列化器
        YamlChangeLogSerializer serializer = new YamlChangeLogSerializer();
        try (OutputStream outputStream = new FileOutputStream("zngk_dict_%s.yml".formatted(dictType))) {
            serializer.write(List.of(changeSet), outputStream);
        }
    }

}
